package cn.jdk.aqstool;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;

/**
 * 线程栅栏
 *
 * @author summit
 * @since 2021/8/8 20:14
 */
@Slf4j
public class CyclicBarrierTest {

	static CyclicBarrier barrier = new CyclicBarrier(8, new Runnable() {
		@Override
		public void run() {
			System.out.println("ok+++++ ready run!");
		}
	});

	public static void main(String[] args) {
		Executor executor = Executors.newFixedThreadPool(8);
		for (int i = 0; i < 8; i++) {
			executor.execute(new Runner(barrier, "run" + i));
		}
		//log
	}

	@Slf4j
	static class Runner implements Runnable {
		private CyclicBarrier barrier;

		private String name;

		public Runner(CyclicBarrier barrier, String name) {
			this.barrier = barrier;
			this.name = name;
		}

		@Override
		public void run() {
			log.info("{} 准备就绪!", name);
			try {
				barrier.await();
				TimeUnit.SECONDS.sleep(new Random().nextInt(5));
				log.info("{} 结束！！！", name);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
